import { registerMicroApps, runAfterFirstMounted, start } from 'qiankun'
import actions from './action'
import { useUserStore, useTokenStore } from '@glz/utils'
import { PROJECT_KEY,PROJECT_SUB_VITE_TS_PORT,PROJECT_SUB_VITE_JS_PORT,PROJECT_SUB_VUE_JS_PORT,PROJECT_SUB_NUXT_TS_PORT } from '@/config'
import { ElLoading } from 'element-plus'

import 'nprogress/nprogress.css';
import NProgress from 'nprogress';

//import pager from './utils/pager'
//import { pinia } from '@glz/utils'

const useQianKun = () => {

  const loader = (isLoading:boolean) => {
    console.log('loading:',isLoading);
    if (isLoading) {
      NProgress.start();
      console.log(`Loading...`);
    } else {
      NProgress.done();
      console.log(`Load done.`);
    }
  }

  //let loadingInstance:any = null;

  // const loader = (show:boolean) => {
  //   if (show && !loadingInstance) {
  //     loadingInstance = ElLoading.service({ fullscreen: true });
  //   } else if (!show && loadingInstance) {
  //     loadingInstance.close();
  //     loadingInstance = null;
  //   }
  // }

  // const loader = (isLoading:boolean) => {
  //   console.log('loading:',isLoading);
  //   const loading = document.getElementById('global-loading');
  //   if (loading) {
  //     loading.style.display = isLoading ? 'block' : 'none';
  //   }
  // }

  const getMsg = () => {

    const store = useUserStore(PROJECT_KEY)
    const token = useTokenStore(PROJECT_KEY)

    console.log("user:",store.user)

    const globalState = {
      theme: "red",
      language: "en",
      useUserStore: store.user
    };
  
    actions.setGlobalState(globalState)

    const msg = { // 结合下章主应用下发资源给子应用，将pager作为一个模块传入子应用
      data: { token: token.token}, // store.getters, // 从主应用仓库读出的数据
      components: null, // LibraryUi, // 从主应用读出的组件库
      utils: null, // LibraryJs, // 从主应用读出的工具类库
      emitFnc: null, // childEmit, // 从主应用下发emit函数来收集子应用反馈
      // pager, // 从主应用下发应用间通信呼机
      actions,
      setUser:(val:any) => {
        const store_user = useUserStore(PROJECT_KEY)
        store_user.user = val
        console.log('[主應用] 收到子應用更新：', val)
      }
    }

    console.log("msg",msg)
    return msg
  }
 // console.log("msg:", msg)

  const isDev = import.meta.env.VITE_ENV === "dev"

  console.log("isDev:",import.meta.env.VITE_ENV)

  registerMicroApps([
    {
      name:'sub-vite-js',
      entry: isDev ? `//127.0.0.1:${PROJECT_SUB_VITE_JS_PORT}/` : '/sub-vite-js/', 
      // entry:  `//127.0.0.1:${PROJECT_SUB_VITE_JS_PORT}/`, // dev
      // entry: '/sub-vite-js/',  // build 
      container: '#subapp-container',
      activeRule: '/vite-js',
      props: () => getMsg(),
      loader: loader
    },
    {
      name:'sub-vite-ts',
      entry: isDev ? `//127.0.0.1:${PROJECT_SUB_VITE_TS_PORT}/` : '/sub-vite-ts/', 
      // entry: `//127.0.0.1:${PROJECT_SUB_VITE_TS_PORT}/`, // dev
      // entry: '/sub-vite-ts/', // build 
      container: '#subapp-container',
      activeRule: '/vite-ts',
      props: () => getMsg(),
      loader: loader
    },
    {
      name:'sub-vue-js',
      entry: isDev ? `//127.0.0.1:${PROJECT_SUB_VUE_JS_PORT}/` : '/sub-vue-js/', // dev
      // entry: `//127.0.0.1:${PROJECT_SUB_VUE_JS_PORT}/`, // dev
      // entry: '/sub-vue-js/', // build 
      container: '#subapp-container',
      activeRule: '/vue-js',
      props: () => getMsg(),
      loader: loader
    },
    {
      name:'sub-nuxt-ts',
      entry: isDev ? `//127.0.0.1:${PROJECT_SUB_NUXT_TS_PORT}/` : '/sub-nuxt-ts/', // dev
      // entry: `//127.0.0.1:${PROJECT_SUB_VUE_JS_PORT}/`, // dev
      // entry: '/sub-vue-js/', // build 
      container: '#subapp-container',
      activeRule: '/nuxt-ts',
      props: () => getMsg(),
      loader: loader
    }
  ],{
    beforeLoad:[
      async () => {
        NProgress.start();
        console.log('加載前');
      }
    ],
    beforeMount: [
      async () => {
        console.log('掛載前');
      }
    ],
    afterMount: [
      async () => {
        NProgress.done();
        console.log('掛載後');
      }
    ],
    beforeUnmount: [
      async () => {
        console.log('銷毀前');
      }
    ],
    afterUnmount: [
      async () => {
        NProgress.remove();
        console.log('銷毀後');
      }
    ]
  }
)

  // qiankun 中處理樣式 如何處理的
  // 默認情況下切換應用 她會採用動態樣式表，加載的時候添加樣式 刪除的時候卸載樣式 （子應用之間的樣式隔離）

  // 主應用和子應用 如何隔離 （我們可以通過BEM規範） -> (css-modules) 動態生成一個前綴 （並不是完全隔離）
  // shadowDOM video 標籤中的快進 放大功能 增加全局樣式就會有問題

  /**
   * @name 启动微前端， 已經放到子頁面進行啟動了
   */
  // start({
  //   sandbox: {
  //     // experimentalStyleIsolation: true,
  //     strictStyleIsolation: true
  //   }
  // })

  /**
  * @name 设置默认进入的子应用
  * @param {String} 需要进入的子应用路由前缀
  */
  // setDefaultMountApp('/app1')

  /**
   * @name 微前端启动进入第一个子应用后回调函数
   */
  runAfterFirstMounted(() => {
    console.log('[MainApp] first app mounted')
  })

  start()
  
}

export { useQianKun }
